package link.jfire.jnet.server.storage;

import link.jfire.baseutil.reflect.ReflectUtil;
import sun.misc.Unsafe;

@SuppressWarnings("restriction")
public class Entry
{
    private static Unsafe           unsafe          = ReflectUtil.getUnsafe();
    private volatile int            takeState;
    private static long             takeStateoffset = ReflectUtil.getFieldOffset("takeState", Entry.class);
    public static final int         FREEFORUSE      = 0;
    public static final int         TAKEN           = 1;
    private volatile ServerInternalResult serverInternalResult;
                                    
    /**
     * 设置新的数据，会将状态刷新为freeforuse
     * 
     * @param actionType
     * @param command
     * @param serverChannelInfo
     */
    public void setNewData(ServerInternalResult serverInternalResult)
    {
        this.serverInternalResult = serverInternalResult;
        // 这里无需插入写写屏障。虽然这四个语句可能会乱序执行，但是由于生产者需要发布，消费者才能看到。而这些操作都发生在发布之前，所以保证了可以被消费者正确发现
        takeState = FREEFORUSE;
    }
    
    /**
     * 获取该消息的使用权，true代表成功，false代表失败
     * 
     * @return
     */
    public boolean take()
    {
        if (takeState == FREEFORUSE)
        {
            return unsafe.compareAndSwapInt(this, takeStateoffset, FREEFORUSE, TAKEN);
        }
        else
        {
            return false;
        }
    }
    
    public ServerInternalResult getInternalResult()
    {
        return serverInternalResult;
    }
    
    public void setInternalResult(ServerInternalResult serverInternalResult)
    {
        this.serverInternalResult = serverInternalResult;
    }
    
}
